/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86185
 * Date: 2023-06-18
 * Time: 20:05
 */

import java.io.*;

/**
 * 缓冲流的作用:提升文件读写的效率
 * 处理非文本文件:BufferedInputStream  read(byte[] buffer)
 *             BufferedOutputStream  write(byte[] buffer, 0, len)
 * 处理文本文件:BufferedReader read(char[] cBuffer) / readLine()
 *           BufferedWriter write(char[] cBuffer, 0, len)
 *
 */
public class BufferedStream {
    /**
     * 使用BufferedInputStream BufferedOutputStream 复制一个图片
     */
    public static void main(String[] args){
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        BufferedInputStream bufferedInputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        try {
            File src = new File("test.jpg");
            File dest = new File("test_copy2.jpg");
            //2.创建相关的字节流,缓冲流
            fileInputStream = new FileInputStream(src);
            fileOutputStream = new FileOutputStream(dest);
            bufferedInputStream = new BufferedInputStream(fileInputStream);
            bufferedOutputStream = new BufferedOutputStream(fileOutputStream);

            //3.数据的读写
            byte[] buff = new byte[1024];//1kb
            int len;//记录每次读入到buff中的字节个数
            while ((len = bufferedInputStream.read(buff)) != -1) {
                bufferedOutputStream.write(buff, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //外层流的关闭
            //由于外层流的关闭也会自动地对内层流进行关闭操作,所以可以省略内层流关闭
            try {
                if (bufferedInputStream != null) {
                    bufferedInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (bufferedOutputStream != null) {
                    bufferedOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            //内层流的关闭
//            fileInputStream.close();
//            fileOutputStream.close();
        }
        //4.关闭流资源

    }
}
